package service

import (
	"context"
	v1 "server_go/api/v1"
	"server_go/internal/repository"
	"time"

	"golang.org/x/crypto/bcrypt"
)

type AdminService interface {
	Login(ctx context.Context, req *v1.LoginAdminRequest) (string, error)
}

func NewAdminService(service *Service, adminRepo repository.AdminRepository) AdminService {
	return &adminService{
		Service:   service,
		adminRepo: adminRepo,
	}
}

type adminService struct {
	*Service
	adminRepo repository.AdminRepository
}

func (s *adminService) Login(ctx context.Context, req *v1.LoginAdminRequest) (string, error) {
	//1.判断账号密码是否正确
	admin, err := s.adminRepo.GetAccount(ctx, req.Account)
	if err != nil {
		return "", v1.ErrInternalServerError
	}

	if admin == nil {
		return "", v1.ErrAccount
	}

	err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password))
	if err != nil {
		return "", v1.ErrAccount
	}

	//2.生成token
	token, err := s.jwt.GenToken(int(admin.ID), time.Now().Add(time.Hour*24*7))
	if err != nil {
		return "", v1.ErrInternalServerError
	}

	//3.返回token
	return token, nil
}
